package factorys;

import entity.Person;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * @author Rain
 * @Description : 模拟Spring
 * @date  2022/08/17 15:55
 */
public class MyBeanFactory {
    /**
     * 用于存储对象
     */
    private static Map<String, Object> map = new HashMap<>();

    static {
        Properties properties = new Properties();

        Person p = null;
        try {
            properties.load(PersonFactory.class.getResourceAsStream("../person.properties"));
            //获取properties中所有的key
            Set<String> keys = properties.stringPropertyNames();
            //遍历set,通过key获取value,并通过反射创建对象
            for (String key : keys) {
                String val = properties.getProperty(key);
                Object o = Class.forName(val).newInstance();
                //将对象存入map集合中,key=properties.key,value=对象
                map.put(key, o);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据传入的值返回map集合中的对象
     * @param name 对象类名
     * @return 指定对象
     */
    public static Object getBean(String name) {
        return map.get(name);
    }
}
